package com.renli.servlet.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.renli.utils.ApiResult;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String operation = req.getParameter("operation");
        Method[] methods = this.getClass().getDeclaredMethods();
        boolean invoked = false;
        for (Method method : methods) {
            if (method.getName().equals(operation)) {
                try {
                    method.invoke(this, req, resp);
                } catch (Exception e) {
                    Throwable rootCause = findRootCause(e);
                    if (rootCause != null) {
                        StringWriter sw = new StringWriter();
                        PrintWriter pw = new PrintWriter(sw);
                        rootCause.printStackTrace(pw);
                        String stackTrace = sw.toString();
                        System.err.println(stackTrace);
                        sendJsonResponse(resp, new ApiResult<>(500, "乱搞个鸡8、草泥马  error了。", stackTrace));
                    }
                }
                invoked = true;
            }
        }
        if (!invoked) {
            sendJsonResponse(resp, new ApiResult<>(500, "别tm乱访问，未指定operation或没有该方法。", null));
        }
    }

    private Throwable findRootCause(Throwable throwable) {
        Throwable rootCause = throwable;
        while (rootCause.getCause() != null) {
            rootCause = rootCause.getCause();
        }
        return rootCause;
    }

    //    响应json
    protected static void sendJsonResponse(HttpServletResponse response, Object responseObject) throws IOException {
        // 使用 ObjectMapper 将 Java 对象转换为 JSON 字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(responseObject);

        // 设置响应的内容类型为 "application/json"
        response.setContentType("application/json");

        // 将 JSON 字符串作为响应的内容写入输出流
        PrintWriter out = response.getWriter();
        out.print(json);
        out.flush();
    }

}
